﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using FantastPlatform.Framework;
using FantastPlatform.Framework.Core;
using FantastPlatform.Framework.Model;
using FantastPlatform.Decision.IService;
using FantastPlatform.Decision.IModel;
using FantastPlatform.Decision.Model;
using FantastPlatform.Framework.IService;
using FantastPlatform.Framework.IModel;
using FantastPlatform.Framework.Common;

namespace FantastPlatform.Decision.UI.Service
{
    public partial class MeetingViewService : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            LoginEmployee = Session["User"] as FantastPlatform.Framework.Model.Employee;
            IMeetingService meetingService = ServiceFactory.CreateService<IMeetingService>();

            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            group.Conditions.Add(enableCondition);
          
            int totalCount = 0;
            switch (Action)
            {
                case "Add":
                    string data = Data;
                    IMeeting meeting = (IMeeting)JsonToEntity<Meeting>(RepairString(data));
                    bool isSendMsg = !string.IsNullOrEmpty(meeting.IsSendMsg);
                    GetLeaders(meeting, isSendMsg);
                    if (meeting.Id == 0)
                    {
                        meeting.Enable = true;
                        if (LoginEmployee != null)
                        {
                            meeting.Writer = LoginEmployee;
                            meeting.CreateDate = DateTime.Now;
                            meetingService.Create(meeting);

                            ReturnSuccessMessage("保存会议成功");
                        }
                        else
                        { ReturnErrorMessage("未登陆或数字证书已过期！"); }
                    }
                    else
                    {
                        IMeeting OldMeeting = meetingService.Get(meeting.Id);
                        if (OldMeeting.MeetingDate < DateTime.Now)
                        {
                            ReturnErrorMessage("不能对历史记录进行修改");
                            return;
                        }
                        else
                        {
                            OldMeeting.ModifyDate = DateTime.Now;
                            OldMeeting.MeetingDate = meeting.MeetingDate;
                            OldMeeting.Name = meeting.Title;
                            OldMeeting.Title = meeting.Title;
                            OldMeeting.Content = meeting.Content;
                            OldMeeting.Persons = meeting.Persons;
                            meetingService.Update(OldMeeting);
                            ReturnSuccessMessage("更新会议成功");
                        }
                    }
                    break;
                case "Search":

                    IList<Sort> sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                    IList<IMeeting> meetingList = meetingService.Search(group, sorts, PageSize, SelfPage, out totalCount);

                    var obj = from n in meetingList
                              select new
                              {
                                  Id = n.Id,
                                  Title = n.Title,
                                  Content = n.Content,
                                  PoliceName = n.Writer.Name,
                                  MeetingDate = n.MeetingDate.ToString(),
                                  Writer = n.Writer.Name,
                                  Leaders = string.Join(",", (from p in n.Persons
                                                              where p.Enable = true
                                                              select p.Name.ToString()).ToArray<string>()),
                                  Receives = string.Join("</br>", (from o in GetLeadersReceive(n)
                                                                   where o.Enable = true
                                                                   select o.Person.Name + (o.Receive == true ? "(已确认收到)" : "(未确认收到)")).ToArray<string>())
                              };
                    ReturnList(totalCount, obj.ToList());
                    break;
                case "SearchByCondition":
                    string Searchjson = RepairString(Data);
                    meeting = JsonToEntity<Meeting>(Searchjson);
                    enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
                    Condition condition1 = new Condition() { Type = typeof(string).FullName, Field = "Name", Value1 = '%' + meeting.Name + '%', Comparison = Comparisons.Like, Relation = Relations.And };
                    group.Conditions.Add(enableCondition);
                    group.Conditions.Add(condition1);
                    sorts = new List<Sort>();
                    sorts.Add(new Sort() { Field = "CreateDate", Order = Orders.Desc });
                    meetingList = meetingService.Search(group, sorts, PageSize, SelfPage, out totalCount);
                    obj = from n in meetingList
                          select new
                          {
                              Id = n.Id,
                              Title = n.Title,
                              Content = n.Content,
                              PoliceName = n.Writer.Name,
                              MeetingDate = n.MeetingDate.ToString(),
                              Writer = n.Writer.Name,
                              Leaders = string.Join(",", (from p in n.Persons
                                                          where p.Enable = true
                                                          select p.Name.ToString()).ToArray<string>()),
                              Receives = string.Join("</br>", (from o in GetLeadersReceive(n)
                                                               where o.Enable = true
                                                               select o.Person.Name + (o.Receive == true ? "(已确认收到)" : "(未确认收到)")).ToArray<string>())
                          };
                    var objList = obj.ToList();
                    ReturnList(objList.Count, objList);
                    break;
                case "Get":
                    meeting = meetingService.Get(Id);
                    object objMeeting = (new
                                     {
                                         WriterManNumber = meeting.Writer.Code,
                                         Title = meeting.Title,
                                         Content = meeting.Content,
                                         MeetingDate = meeting.MeetingDate,
                                         PoliceCode = meeting.Writer.Code
                                     });
                    ReturnObj2(objMeeting);
                    break;
                case "Delete":
                    if (string.IsNullOrEmpty(Data))
                    {
                        throw new Exception("传入的会议ID为空");
                    }
                    List<int> idList = new List<int>();
                    string[] idStrList = Data.Split(',');
                    foreach (string id in idStrList)
                    {
                        idList.Add(int.Parse(id));
                    }
                    meetingService.Delete(idList);
                    ReturnSuccessMessage("删除会议成功");
                    break;
                case "GetLeader":
                    ILeaderTelService empService = ServiceFactory.CreateService<ILeaderTelService>();
                    totalCount = 0;
                    IList<ILeaderTel> employeeList = empService.LoadList(null, int.MaxValue, 1, out totalCount);
                    object[] employeeObjs = (from emp in employeeList
                                             select new
                                             {
                                                 Id = emp.Id,
                                                 Name = emp.Name,
                                                 Code = emp.PoliceCode
                                             }).ToArray();
                    ReturnList(totalCount, employeeObjs);
                    break;
                case "GetLeadersByMeetingId":
                    IMeeting mt = meetingService.Get(Id);
                    string leaders = string.Join(",", (from p in mt.Persons
                                                       where p.Enable = true
                                                       select p.Code.ToString()).ToArray<string>());
                    ReturnSuccessMessage(leaders);
                    break;
            }
        }
        private void GetLeaders(IMeeting meeting,bool IsSendMsg)
        {
            string[] codes;
            if (!string.IsNullOrEmpty(Request["Leaders"]))
            {
                codes = Request["Leaders"].Split(',');
                if (codes.Length > 0)
                {
                    meeting.Persons = new List<IEmployee>();
                    foreach (string code in codes)
                    {
                        IEmployeeService service = ServiceFactory.CreateService<IEmployeeService>();
                        IEmployee emp = service.Get(code);
                        if (emp != null)
                        {
                            meeting.Persons.Add(emp);
                            SendMessage("|05|" + emp.Code);
                            if (IsSendMsg)
                            {
                                string tel = (from c in emp.Contacts
                                              where c.ContactType.Name == "手机"
                                              select c.Value).FirstOrDefault();
                                if (!string.IsNullOrEmpty(tel))
                                {
                                    MessageManager.SendMessage(tel, "您有新的会议安排：" + meeting.Title + ",请通过决策指挥终端查看详情。（发送人：" + LoginEmployee.Name + ")", LoginEmployee.Code, DateTime.Now);
                                }
                            
                            }

                        }
                    }
                }
            }
        }
        private IList<IMeetingPerson> GetLeadersReceive(IMeeting meeting)
        {
            int total = 0;
            IMeetingPersonService mpService = ServiceFactory.CreateService<IMeetingPersonService>();
            ConditionGroup group = new ConditionGroup();
            Condition enableCondition = new Condition() { Type = typeof(bool).FullName, Field = "Enable", Value1 = true };
            group.Conditions.Add(enableCondition);
            group.Conditions.Add(new Condition() { Field = "Meeting.Id", Type = typeof(int).FullName, Relation = Relations.And, Value1 = meeting.Id });
            IList<Sort> sorts = new List<Sort>();
            sorts.Add(new Sort() { Field = "Receive", Order = Orders.Asc });
            IList<IMeetingPerson> mpList = mpService.Search(group, sorts, int.MaxValue, 1, out total);
            return mpList;

        }
    }
}